const jwt = require('express-jwt');
const jwtSign = require('jsonwebtoken').sign;
const jwtVerify = require('jsonwebtoken').verify;
const axios = require('axios');
const FormData = require('form-data');
const path = require('path');
const fs = require('fs');
const express = require('express');
const { createServer } = require('http');
const { Server } = require('socket.io');
const multer = require('multer');
const cors = require('cors')
const http = require("http");


const appchat = express();
// 跨域
appchat.use(cors())
const server = http.createServer(appchat);
const io = new Server(server, {
  cors: {
    origin: "https://www.xiangzizhuye.cn",
    // methods: ["GET", "POST"],
  },
});
   
module.exports = function (app, response) {
    
    // 初始化存储目录
    const UPLOAD_DIR = path.join(__dirname, "public/chatuploads");
    const MESSAGE_FILE = path.join(__dirname, "messages.json");
    !fs.existsSync(UPLOAD_DIR) && fs.mkdirSync(UPLOAD_DIR, { recursive: true });
    
    // 加载历史消息
    let messages = loadMessages();
    
    // 文件上传配置
    const upload = multer({
      storage: multer.diskStorage({
        destination: (req, file, cb) => cb(null, UPLOAD_DIR),
        filename: (req, file, cb) => cb(null, `${Date.now()}-${file.originalname}`), // 保留原始文件名
      }),
      limits: { fileSize: 100 * 1024 * 1024 },
    });
    
    // 新增图片查询接口
    appchat.get("/chatimages", (req, res) => {
      const { keyword } = req.query;
    
      // 从消息记录中筛选图片
      const images = messages
        .filter((msg) => msg.type === "image")
        .map(({ content, timestamp }) => ({
          url: content,
          filename: path.basename(content),
          timestamp,
        }))
        .filter((img) => {
          if (!keyword) return true;
          return img.filename.toLowerCase().includes(keyword.toLowerCase());
        });
    
      res.json({ code: 200, data: images });
    });
    
    // 文件上传接口
    appchat.post("/chatupload", upload.single("file"), (req, res) => {
      // 构造消息对象
      const newMsg = {
        type: req.file.mimetype.split("/")[0],
        content: `/chatuploads/${req.file.filename}`,
        timestamp: Date.now(),
        id: generateId(),
      };
    
      // 保存到消息系统
      messages.push(newMsg);
      saveMessages();
    
      // 广播给所有客户端
      io.emit("message", newMsg);
    
      res.json(newMsg);
    });
    
    // Socket.io逻辑
    io.on("connection", (socket) => {
    //   console.log("连接");
      socket.emit("history", messages);
    
      socket.on("message", (msg) => {
        const newMsg = {
          ...msg,
          timestamp: Date.now(),
          id: generateId(),
        };
    
        messages.push(newMsg);
        saveMessages();
        io.emit("message", newMsg);
      });
    });
    
    io.on("disconnect", (reason) => {
      console.log(
        `[${new Date().toISOString()}] 客户端断开 ID: ${io.id} 原因: ${reason}`
      );
    });
    
    // 静态文件服务
    appchat.use( express.static(path.join(__dirname, "public")));
    
    // 启动服务
    server.listen(3000, () => console.log("socket in http://localhost:3000"));
    
    // 工具函数
    function generateId() {
      return Date.now().toString(36) + Math.random().toString(36).substr(2);
    }
    
    function loadMessages() {
      try {
        return JSON.parse(fs.readFileSync(MESSAGE_FILE));
      } catch {
        return [];
      }
    }
    
    function saveMessages() {
      fs.writeFileSync(MESSAGE_FILE, JSON.stringify(messages));
    }
    
    appchat.get("/chatclearall", (req, res) => {
      fs.readdir(UPLOAD_DIR, (err, files) => {
        files.forEach((file) => {
          const filePath = path.join(UPLOAD_DIR, file);
          const stat = fs.statSync(filePath);
          fs.unlinkSync(filePath);
          // 同步清理消息记录
          messages = messages.filter(
            (msg) => !(msg.type === "image" && msg.content?.includes(file))
          );
          saveMessages();
        });
    
        // 清空消息记录
        messages = []; // 直接清空数组
        saveMessages(); // 保存空数组到文件
    
        res.status(200).send("所有内容和记录已清除");
      });
    });
    
}